package com.netty.config;

import com.alibaba.fastjson.JSON;
import com.netty.CIMWebSocketRequestHandler;
import com.netty.ImWebsocketServer;
import com.netty.config.properties.CIMProperties;
import com.netty.constant.Constants;
import com.netty.constant.ImChannels;
import com.netty.model.SentBody;
import io.netty.channel.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.data.redis.core.RedisTemplate;

import java.net.UnknownHostException;


@Slf4j
public class CIMWebSocketConfig implements CIMWebSocketRequestHandler {

	private ImChannels imChannels;

	private RedisTemplate redisTemplate;

	private String SERVER = "server:user";

	public CIMWebSocketConfig(ImChannels imChannels,RedisTemplate redisTemplate) throws UnknownHostException {
		this.imChannels = imChannels;
		this.redisTemplate = redisTemplate;
	}

	@Bean
	public ImWebsocketServer getNioWebsocketAcceptor(CIMProperties properties) {
		return new ImWebsocketServer(this,properties.getWebsocketPort());
	}
	@Override
	public void channelActive(Channel channel) {
		System.out.println("链接成功");
	}

	@Override
	public void channelRead0(Channel channel, SentBody sentBody) {
		switch (sentBody.getKey()){
			case Constants.ImserverConfig.CLIENT_CONNECT_BIND:

				String uid = sentBody.get("uid");
				channel.attr(Constants.SessionConfig.UID).set(uid);
				channel.attr(Constants.SessionConfig.CHANNEL).set(Constants.ImserverConfig.WEBSOCKET);
				/*
				 * 添加到内存管理
				 */
				imChannels.add(channel);
				String ips = channel.attr(Constants.SessionConfig.SIPS).get();
				Integer port = channel.attr(Constants.SessionConfig.SPORT).get();
				redisTemplate.opsForHash().put(SERVER,uid,ips+":"+port);
				/*
				 *向客户端发送bind响应
				 */

				SentBody replys = new SentBody();
				replys.setKey(Constants.ImserverConfig.CLIENT_CONNECT_BIND);
				replys.put("body", JSON.toJSONString(imChannels.findAll()));
				channel.writeAndFlush(replys);
				break;
			case Constants.ImserverConfig.CLIENT_CONNECT_CLOSED:
				channelUnregistered(channel);
				break;
		}
	}


	@Override
	public void channelUnregistered(Channel channel) {
		/*
		 *向客户端发送bind响应
		 */
		SentBody replys = new SentBody();
		replys.setKey(Constants.ImserverConfig.CLIENT_CONNECT_CLOSED);
		channel.writeAndFlush(replys);
		String uid = channel.attr(Constants.SessionConfig.UID).get();
		redisTemplate.opsForHash().delete(SERVER+"user",uid);
		imChannels.delete(channel);

	}
}
